package com.drama.api.sys.version.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ZipUtil;
import com.drama.api.base.Constants;
import com.drama.api.base.R;
import com.drama.api.base.Type;
import com.drama.api.sys.version.dao.SysVersionDao;
import com.drama.api.sys.version.domain.po.SysVersionPO;
import com.drama.api.sys.version.domain.vo.SysVersionAddVO;
import com.drama.api.sys.version.domain.vo.SysVersionSearchVO;
import com.drama.api.sys.version.domain.vo.SysVersionVO;
import com.drama.api.sys.version.service.ISysVersionService;
import com.drama.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;


@Service
@Transactional
@Slf4j
public class SysVersionServiceImpl implements ISysVersionService {

    @Autowired
    private SysVersionDao versionDao;


    @Override
    public List<SysVersionVO> getList(SysVersionSearchVO searchVO) {
        return versionDao.getList(searchVO);
    }

    @Override
    public void add(SysVersionAddVO vo) {
        SysVersionPO sysVersionPO=new SysVersionPO();
        BeanUtils.copyProperties(vo, sysVersionPO);
        sysVersionPO.setId(IdUtil.getSnowflakeNextIdStr());
        sysVersionPO.setVersionDate(new Date());
        int i = versionDao.insertSelective(sysVersionPO);
        if (i == Constants.SQL_RETURN_SUCCESS) {
            throw new BusinessException(Type.FAIL);
        }
    }


    public static void main(String[] args) {
        String timeDirectory = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        System.out.println(timeDirectory);
    }


    @Override
    public R updateWeb(MultipartFile file) throws IOException {
        String path= "/data/ui/new/manage";
//        String path= System.getProperty("user.dir")+"/ui";
//        String zipPath= System.getProperty("user.dir")+"/uiZip";
        String zipPath= "/data/ui/new/manageZip";
        String timeDirectory = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        File dest = new File(zipPath+"/"+timeDirectory+file.getOriginalFilename());
        if (!dest.getParentFile().exists()) {// 检测是否存在目录
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);
//        ZipUtil.zip(path, zipPath+"/old"+timeDirectory+file.getOriginalFilename());
        FileUtil.del(path);
        ZipUtil.unzip(zipPath+"/"+timeDirectory+file.getOriginalFilename(),path);
        return new R();
    }
}